package com.paishen.common.util;


import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Binder;
import android.os.Build;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.paishen.common.LibCommon;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class BaseUtil {
    /**
     * 自定义view中使用
     *
     * @param dpValue
     * @return
     */
    public static final int dip2px(float dpValue) {
        if (LibCommon.appContext() != null) {
            final float scale = LibCommon.appContext().getResources().getDisplayMetrics().density;
            return (int) (dpValue * scale + 0.5f);
        }
        return 0;
    }

    //    /**
//     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
//     */
//    public static int px2dip(float pxValue) {
//        if (App.i() != null) {
//            final float scale = App.i().getResources().getDisplayMetrics().density;
//            return (int) (pxValue / scale + 0.5f);
//        }
//        return 0;
//    }
//
    public static final int getStatusBarHeight() {
        if (LibCommon.appContext() == null) {
            LogUtil.e("BaseUtil getStatusBarHeight context empty");
            return -1;
        }
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = LibCommon.appContext().getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 隐藏输入法
     *
     * @param context Activity
     */
    public static final void hideSoftInputFromWindowAlways(Activity context) {
        if (context.getCurrentFocus() != null) {
            ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(context.getCurrentFocus()
                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public static final void showToast(String text) {
        if (LibCommon.appContext() == null) {
            LogUtil.e("BaseUtil showToast context empty");
            return;
        }
        Toast.makeText(LibCommon.appContext().getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    public static final void showToast(int resId) {
        if (LibCommon.appContext() == null) {
            LogUtil.e("BaseUtil showToast context empty");
            return;
        }
        Toast.makeText(LibCommon.appContext().getApplicationContext(), resId, Toast.LENGTH_SHORT).show();
    }

    public static final String getAppVersionName() {
        if (LibCommon.appContext() == null) {
            LogUtil.e("BaseUtil getAppVersionName context empty");
            return "";
        }
        try {
            return LibCommon.appContext() != null ? LibCommon.appContext().getPackageManager().getPackageInfo(LibCommon.appContext().getPackageName(), 0).versionName : "";
        } catch (Exception e) {
            return "";
        }
    }

    public static final int getAppVersionCode() {
        if (LibCommon.appContext() == null) {
            LogUtil.e("BaseUtil getAppVersionCode context empty");
            return -1;
        }
        try {
            return LibCommon.appContext() != null ? LibCommon.appContext().getPackageManager().getPackageInfo(LibCommon.appContext().getPackageName(), 0).versionCode : -1;
        } catch (Exception e) {
            return -1;
        }
    }

    public static final String getDeviceInfo() {
        StringBuffer sb = new StringBuffer();
        String brand_en = Build.BRAND;
        if ("三星".equals(brand_en)) {
            brand_en = "SAMSUNG";
        }
        sb.append("PniwanApp/").append(BaseUtil.getAppVersionName()).append(" (").append(brand_en)
                .append(" ").append(Build.MODEL).append("; Android ").append(Build.VERSION.RELEASE).append(")");
        return sb.toString();
    }

    /**
     * app权限状态检测
     *
     * @param op
     * @return 返回 0 就代表有权限，1代表没有权限，-1函数出错啦, -2表示权限检测失败
     */
    public static final int checkOp(int op) {
        if (LibCommon.appContext() == null) {
            LogUtil.e("BaseUtil checkOp context empty");
            return -1;
        }

        final int version = Build.VERSION.SDK_INT;
        if (version >= Build.VERSION_CODES.KITKAT) {
            Object object = LibCommon.appContext().getSystemService("appops");
            Class c = object.getClass();
            try {
                Class[] cArg = new Class[3];
                cArg[0] = int.class;
                cArg[1] = int.class;
                cArg[2] = String.class;
                Method lMethod = c.getDeclaredMethod("checkOp", cArg);
                return (Integer) lMethod.invoke(object, op, Binder.getCallingUid(), LibCommon.appContext().getPackageName());
            } catch (Exception e) {
                e.printStackTrace();
                return -1;
            }
        } else {
            return -2;
        }
    }

    /**
     * 如果string包含特殊字符就会返回true
     */
    public static final boolean isConSpeCharacters(String string) {
        if (string.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() == 0) {
            //不包含特殊字符
            return false;
        }
        return true;
    }

//    public static Bitmap compressImage(Bitmap image) {
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
//        int options = 100;
//        while (baos.toByteArray().length / 1024 > 200) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
//            baos.reset();//重置baos即清空baos
//            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
//            options -= 10;//每次都减少10
//        }
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
//        return bitmap;
//    }
//
//    public static boolean bitmapToFile(Bitmap bitmap, String filePath) {
//        boolean isSuccess = false;
//        if (bitmap == null) {
//            return isSuccess;
//        }
//        OutputStream out = null;
//        try {
//            out = new BufferedOutputStream(new FileOutputStream(filePath), 8 * 1024);
//            isSuccess = bitmap.compress(Bitmap.CompressFormat.PNG, 70, out);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } finally {
//            if (out != null) try {
//                out.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return isSuccess;
//    }

    public static final boolean setStatusBarDarkMode(boolean darkmode, Activity activity) {
        if ("Xiaomi".equalsIgnoreCase(Build.BRAND)) {
            Class<? extends Window> clazz = activity.getWindow().getClass();
            try {
                int darkModeFlag = 0;
                Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
                return true;
            } catch (Exception e) {
                LogUtil.e("Xiaomi setStatusBarDarkIcon: failed");
                return false;
            }
        } else if ("MeiZu".equalsIgnoreCase(Build.BRAND)) {
            Window window = activity.getWindow();
            if (window != null) {
                try {
                    WindowManager.LayoutParams lp = window.getAttributes();
                    Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                    Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
                    darkFlag.setAccessible(true);
                    meizuFlags.setAccessible(true);
                    int bit = darkFlag.getInt(null);
                    int value = meizuFlags.getInt(lp);
                    if (darkmode) {
                        value |= bit;
                    } else {
                        value &= ~bit;
                    }
                    meizuFlags.setInt(lp, value);
                    window.setAttributes(lp);
                    return true;
                } catch (Exception e) {
                    LogUtil.e("MeiZu setStatusBarDarkIcon: failed");
                    return false;
                }
            }
        }
        return false;
    }
}
